package com.bounds.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.RowCallbackHandler;

import com.bounds.dao.HospitalDao;
import com.bounds.entity.Hospital;
import com.bounds.entity.Pager;

public class HospitalDaoImpl extends BaseDaoImpl<Hospital> implements HospitalDao {

	@Override
	public List<Hospital> qryHospitals(Hospital hospital) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT ID,NAME FROM hospital WHERE 1=1 ");
		List<Object> params = new ArrayList<Object>();
		if(hospital != null){
			if(hospital.getId() != 0){
				sql.append(" AND ID =? ");
				params.add(hospital.getId());
			}
			if(StringUtils.isNotBlank(hospital.getName())){
				sql.append(" AND NAME = ? ");
				params.add(hospital.getName());
			}
		}
		final List<Hospital> list = new ArrayList<Hospital>();
		this.getJdbcTemplate().query(sql.toString(), params.toArray(), new RowCallbackHandler() {		
			@Override
			public void processRow(ResultSet rs) throws SQLException {
				Hospital hospital = new Hospital();
				setHospital(rs,hospital);
				list.add(hospital);
			}
		});
		return list;
	}
	
	private void setHospital(ResultSet rs,Hospital hospital) throws SQLException{
		hospital.setId(rs.getInt("id"));
		hospital.setName(rs.getString("name"));
	}

	@Override
	public Pager<Hospital> qryHospitalsForPager(Hospital hospital,int pageNo,int pageSize) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT id,name FROM hospital WHERE 1=1 ");
		List<Object> params = new ArrayList<Object>();
		if(hospital != null){
			if(hospital.getId() != 0){
				sql.append(" AND id =? ");
				params.add(hospital.getId());
			}
			if(StringUtils.isNotBlank(hospital.getName())){
				sql.append(" AND name LIKE ? ");
				params.add("%"+hospital.getName()+"%");
			}
		}

		this.initPager();
		this.setPageNo(pageNo);
		this.setPageSize(pageSize);	
		int rowCount = this.getRowCount(sql.toString(), params.toArray());
		if(rowCount>0){		
			final List<Hospital> list = new ArrayList<Hospital>();
			this.getJdbcTemplate().query(getExecuteSQL(sql.toString()), params.toArray(), new RowCallbackHandler() {		
				@Override
				public void processRow(ResultSet rs) throws SQLException {
					Hospital hospital = new Hospital();
					setHospital(rs,hospital);
					list.add(hospital);
				}
			});
			this.setData(list);
		}
		return this.getPager();
	}

	@Override
	public int addHospital(Hospital hospital) {
		String sql = "insert into hospital(name) values(?)";
		return this.getJdbcTemplate().update(sql,new Object[]{hospital.getName()});
	}

	@Override
	public int deleteHospital(int id) {
		return this.getJdbcTemplate().update("delete from hospital where id="+id);
	}
	
	

}
